package list;

import java.util.Arrays;
import java.util.Collections;

public class LinkedNode<T> {
    T value;
    LinkedNode<T> nextNode;

    LinkedNode(T value, LinkedNode<T> nextNode) {
        this.value = value;
        this.nextNode = nextNode;
    }

    @Override
    public String toString() {
        return "LinkedNode{" +
                "value=" + value +
                ", nextNode=" + nextNode +
                '}';
    }

    public static <T> void printTheLinkedNodes(LinkedNode<T> nodeToStartWith) {
        if (nodeToStartWith == null) {
            System.out.print("null");
            return;
        }
        System.out.print(nodeToStartWith.value);
        System.out.print("--> ");
        printTheLinkedNodes(nodeToStartWith.nextNode);
    }

    public static <T> LinkedNode<T> createLinkedNodesList(T... nodeValues) {
        LinkedNode<T> headOfNodesList = null;
        Collections.reverse(Arrays.asList(nodeValues));
        for (T nodeValue : nodeValues) {
            headOfNodesList = new LinkedNode<T>(nodeValue, headOfNodesList);
        }
        return headOfNodesList;
    }

    public static <T> LinkedNode<T> revertLinkedNodesList(LinkedNode<T> headOfList) {
        if (headOfList == null) return null;
        if (headOfList.nextNode == null) return headOfList;

        LinkedNode<T> prev = null;
        LinkedNode<T> current = headOfList;
        do {
            LinkedNode<T> next = current.nextNode;
            current.nextNode = prev;
            prev = current;
            current = next;
        } while (current.nextNode != null);
        current.nextNode = prev;
        return current;
    }


    public static void main(String[] args) throws InterruptedException {
        final LinkedNode<Integer> nodesList = LinkedNode.createLinkedNodesList(1, 2, 3, 4, 5, 6, 7, 8, 9);
        System.out.print("Head:--> ");
        LinkedNode.printTheLinkedNodes(nodesList);
        System.out.println();
        System.out.println("=======================");

        System.out.print("Head:--> ");
        LinkedNode.printTheLinkedNodes(LinkedNode.revertLinkedNodesList(nodesList));
    }
}
